package com.googlecode.c4e.ui.views;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.part.ViewPart;

import com.googlecode.c4e.api.Registry;
import com.googlecode.c4e.api.model.BuildResult;
import com.googlecode.c4e.api.model.Project;
import com.googlecode.c4e.ui.ContinuumPlugin;

public class BuildHistoryView extends ViewPart {

	public static final String VIEW_ID = "com.googlecode.c4e.ui.views.BuildHistoryView";

	private TableViewer viewer;
	private Action doubleClickAction;

	public void showHistoryFor(Project project) {
		viewer.setInput(project);
		viewer.refresh();
		Table table = viewer.getTable();
		for (int i = 0; i < table.getColumnCount(); i++) {
			table.getColumn(i).pack();
		}
	}

	/*
	 * The content provider class is responsible for providing objects to the
	 * view. It can wrap existing objects in adapters or simply return objects
	 * as-is. These objects may be sensitive to the current input of the view,
	 * or ignore it and always show the same content (like Task List, for
	 * example).
	 */

	class ViewContentProvider implements IStructuredContentProvider {
		private Project project;

		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
			if (newInput instanceof Project) {
				project = (Project) newInput;
			}
		}

		public void dispose() {
		}

		public Object[] getElements(Object parent) {
			if (project == null) {
				return new Object[0];
			}
			try {
				return Registry.getDefault().listBuildResults(project)
						.toArray();
			} catch (Exception e) {
				e.printStackTrace();
				return new Object[0];
			}
		}
	}

	class ViewLabelProvider extends LabelProvider implements
			ITableLabelProvider {
		public String getColumnText(Object obj, int index) {
			BuildResult res = (BuildResult) obj;
			switch (index) {
			case 0:
				if (res.getBuildNumber() == 0) {
					return "";
				} else {
					return String.valueOf(res.getBuildNumber());
				}
			case 1:
				return null;
			default:
				return null;
			}
		}

		public Image getColumnImage(Object obj, int index) {
			BuildResult res = (BuildResult) obj;
			if (index == 1) {
				// TODO this is a memory leak, find a better way to do it!
				return ContinuumPlugin.getDefault()
						.getImageDescriptorForProjectState(res.getState())
						.createImage();

			} else {
				return null;
			}
		}
	}

	/**
	 * The constructor.
	 */
	public BuildHistoryView() {
	}

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setInput(getViewSite());
		// Table table = new Table(parent);
		new TableColumn(viewer.getTable(), SWT.LEFT).setText("Build Number");
		new TableColumn(viewer.getTable(), SWT.LEFT).setText("State");
		viewer.getTable().setHeaderVisible(true);
		viewer.getTable().setLinesVisible(true);
		// GridData data = new GridData(GridData.FILL_BOTH);
		// data.horizontalIndent = 0;
		// data.verticalIndent = 0;
		// viewer.getTable().setLayoutData(data);
		// TableLayout layout = new TableLayout();
		// viewer.getTable().setLayout(layout);
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				BuildHistoryView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
	}

	private void fillContextMenu(IMenuManager manager) {
	}

	private void fillLocalToolBar(IToolBarManager manager) {
	}

	private void makeActions() {
		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection) selection)
						.getFirstElement();
				showMessage("Double-click detected on " + obj.toString());
			}
		};
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}

	private void showMessage(String message) {
		MessageDialog.openInformation(viewer.getControl().getShell(),
				"BuildHistoryView", message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}